<script setup lang="ts">
import OrderRequest from '@/request/orderRequest';
import Tools from '@/utils/tools';
import useToast from '@/hooks/useToast';
import to from '@/utils/to';
import { requestPayment } from '@/utils/requestPayment';
import { useAppStore } from '@/store';
import { navigate } from '@/utils/navigate';

type EmitEvents = {
  (event: 'reload'): void;
};

const emits = defineEmits<EmitEvents>();
const props = defineProps<{ data: IOrderDetailInfo }>();
const store = useAppStore();
const showCancelOverlay = ref<boolean>(false);
const message = ref<string>('');
const { showToast } = useToast();

// 订单状态筛选
const orderStateFilter = (state: number) => {
  switch (state) {
    case 1:
      return { message: '订单尚未支付', color: 'c-red' };
    case 4:
      return { message: '订单差价尚未支付', color: 'c-red' };
    case 5:
      return { message: '订单已支付', color: 'c-green' };
    case 15:
      return { message: '订单已退款', color: 'c-color-sec' };
    default:
      return { message: '感谢你使用呼叫器，期待再次光临', color: 'c-black' };
  }
};

// 订单取消
const handleOrderPopupCancel = () => {
  showCancelOverlay.value = false;
  message.value = '';
};

// 订单取消提交
const handleCancelOrderSubmission = () => {
  OrderRequest.SetOrderCancel({ cancelReason: message.value, orderId: props.data.orderId, hasLoading: true }).then((res) => {
    if (res.status === 0) {
      showToast('操作成功', 'success');
      handleOrderPopupCancel();
      emits('reload');
    }
  });
};

// 查询结果
const handleQueryResult = async () => {
  const [err, res] = await to(OrderRequest.GetListKlabReportUrl({ orderId: props.data.orderId, hasLoading: true }));
  if (err) {
    showToast('暂无查询结果');
    return;
  }
  uni.downloadFile({
    url: res.data,
    success: (file) => {
      uni.openDocument({ filePath: file.tempFilePath, fileType: 'pdf', showMenu: true });
    },
  });
};

// 继续支付
const handleContinuePayment = () => {
  OrderRequest.ScanToPayWaitOrder({ orderNos: props.data.orderNo, openId: store.$state.userInfo.openId, hasLoading: true }).then(async (res) => {
    const [payErr] = await to(requestPayment({ ...res.data, provider: 'wxpay', orderInfo: '' }));
    if (payErr) return;
    emits('reload');
  });
};

// 再来一单
const handleRePurchase = () => {
  OrderRequest.BuyAgnGetProdInfo({ orderId: props.data.orderId, hasLoading: true }).then((res) => {
    const productList = res.data.goodsList.map((item) => {
      return { ...item, ...res.data, goodsList: null };
    });
    navigate({ url: `/subcontract/home/submitOrder/index?products=${encodeURIComponent(JSON.stringify(productList))}` });
  });
};
</script>

<template>
  <view class="bg-white c-br mb-12px">
    <van-cell-group inset>
      <van-cell use-label-slot :border="false">
        <view slot="title" class="font-bold font-size-4" :class="orderStateFilter(props.data.payState).color"> {{ orderStateFilter(props.data.payState).message }} </view>
      </van-cell>
      <van-grid clickable :border="true" column-num="4">
        <!-- 继续支付 再来一单 联系商家 致电服务员 结果查询 取消订单 订单跟踪 -->
        <van-grid-item v-if="(props.data.payState === 1 && props.data.orderState !== 15) || (props.data.payState === 4 && props.data.orderState !== 15)" use-slot @click="handleContinuePayment">
          <i class="i-mingcute:wallet-fill font-size-6 mb-2"></i>
          <text>继续支付</text>
        </van-grid-item>
        <van-grid-item v-if="props.data.payState !== 5" use-slot @click="handleRePurchase">
          <i class="i-material-symbols:add-box-outline font-size-6 mb-2"></i>
          <text>再来一单</text>
        </van-grid-item>
        <van-grid-item @click="Tools.callPhone(String(props.data.businessLinkPhone))" use-slot>
          <i class="i-lsicon:service-outline font-size-6 mb-2"></i>
          <text>联系商家</text>
        </van-grid-item>
        <van-grid-item v-if="props.data.waiterPhone" use-slot @click="Tools.callPhone(String(props.data.waiterPhone))">
          <i class="i-mage:phone-call font-size-6 mb-2"></i>
          <text>致电服务员</text>
        </van-grid-item>
        <van-grid-item
          v-if="
            props.data.orderAttrs &&
            Object.values(props.data.orderAttrs)
              .flat()
              .some((item: any) => item.fieldName === 'barcode')
          "
          @click="handleQueryResult"
          use-slot
        >
          <i class="i-f7:doc-text font-size-6 mb-2"></i>
          <text>结果查询</text>
        </van-grid-item>
        <van-grid-item @click="showCancelOverlay = true" v-if="props.data.orderState! < 15 && props.data.errorState !== 3" use-slot>
          <i class="i-material-symbols:cancel-outline font-size-6 mb-2"></i>
          <text>取消订单</text>
        </van-grid-item>
        <van-grid-item v-if="props.data.orderType === 11 && props.data.orderState < 15" use-slot @click="navigate({ url: `/subcontract/order/rescueProgress/index?orderId=${props.data.orderId}` })">
          <i class="i-material-symbols:sos font-size-6 mb-2"></i>
          <text>救援进度</text>
        </van-grid-item>
      </van-grid>
    </van-cell-group>

    <van-popup :show="showCancelOverlay" custom-style="width:90%;" @close="showCancelOverlay = false">
      <view class="c-br c-pd bg-white w-full h-full">
        <view class="text-align-center mb-4">取消订单</view>
        <view>
          <van-field :value="message" @change="message = $event.detail" :border="false" custom-style="background: #f5f5f5" type="textarea" placeholder="请输入留言" :autosize="{ maxHeight: 100, minHeight: 100 }" />
        </view>
        <view class="mt-4 text-align-center">
          <van-button type="default" custom-style="width:44%" size="small" class="mr-4" @click="handleOrderPopupCancel">取 消</van-button>
          <van-button type="primary" custom-style="width:44%" size="small" @click="handleCancelOrderSubmission">提 交</van-button>
        </view>
      </view>
    </van-popup>
  </view>
</template>
